<?php

namespace app\mode;


use app\traits\Singleton;

class Factory
{
    use Singleton;

    /**
     * 单例实例组
     * @var array
     */
    private static array $instances = [];

    /**
     * 创建一个实例类
     * @param string $modeName 模式名字
     * @param bool $newInstance 是否创建新的实例
     * @return object|null
     */
    public function makeNewInstance(string $modeName, bool $newInstance = false): ?object
    {
        ($newInstance or (!isset(self::$instances[$modeName]) or empty(self::$instances[$modeName]))) and self::$instances[$modeName] = self::createInstance($modeName);    //如果不存在实例或者需要重新创建实例
        return self::$instances[$modeName];
    }

    /**
     * 获取单例实例
     * @param string $modeName
     * @return object|null
     */
    private static function createInstance(string $modeName): ?object
    {
        if(!stripos($modeName, '.')){
            return null;
        }
        $arr = explode('.', $modeName);
        if(!file_exists(APP_PATH . '/mode/' . $arr[0] . '/' . ucfirst($arr[1]) . '.php')){
            return null;
        }
        $namespace = 'app\mode\\' . $arr[0] . '\\' . ucfirst($arr[1]);
        if(!class_exists($namespace)){
            return null;
        }
        return new $namespace();
    }

}